package protobuf;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import protobuf.bean.StudentProto;

import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;

public class NettyProtocolBuffersServer {
    public static void main(String[] args) throws CertificateException, SSLException, InterruptedException {



        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup eventGroup = new NioEventLoopGroup();
        new ServerBootstrap()
                .group(bossGroup,eventGroup)
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();

                        ////Protobuf 的编码器和解码器
                        pipeline.addLast(new ProtobufVarint32FrameDecoder());
                        pipeline.addLast(new ProtobufDecoder(StudentProto.Student.getDefaultInstance()));
                        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
                        pipeline.addLast(new ProtobufEncoder());

                        pipeline.addLast(new SimpleChannelInboundHandler<StudentProto.Student>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, StudentProto.Student msg) throws Exception {
                                System.out.println("name:"+msg.getName());
                                System.out.println("age:"+msg.getAge());
                                System.out.println("classes:"+msg.getClasses());
                                StudentProto.Student student = StudentProto.Student.newBuilder()
                                        .setAge(100)
                                        .setClasses("北京市西城区")
                                        .setName("大江东去浪淘尽")
                                        .build();
                                ctx.writeAndFlush(student);

                            }
                        });

                    }
                })
                .bind(8080).sync()
                .channel().closeFuture().sync()
        ;
//        System.out.println("Server start at port : " + "8080");

    }


}
